#!/usr/bin/env python3
"""
反无人机瞄准辅助系统
主程序入口文件

功能:
- 启动GUI界面
- 初始化系统组件
- 处理程序退出
"""

import sys
import os
import logging
from pathlib import Path

# 添加src目录到Python路径
current_dir = Path(__file__).parent
src_dir = current_dir / "src"
sys.path.insert(0, str(src_dir))

try:
    from main_window import MainWindow
except ImportError as e:
    print(f"导入错误: {e}")
    print("请确保所有依赖包已正确安装")
    print("运行: pip install -r requirements.txt")
    sys.exit(1)

def setup_logging():
    """设置日志系统"""
    # 创建logs目录
    logs_dir = current_dir / "logs"
    logs_dir.mkdir(exist_ok=True)
    
    # 配置日志
    log_file = logs_dir / "tank_yolo.log"
    
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(log_file, encoding='utf-8'),
            logging.StreamHandler(sys.stdout)
        ]
    )
    
    logger = logging.getLogger(__name__)
    logger.info("=" * 50)
    logger.info("反无人机瞄准辅助系统启动")
    logger.info("=" * 50)
    
    return logger

def check_dependencies():
    """检查依赖包"""
    required_packages = [
        'cv2', 'numpy', 'PIL', 'ultralytics', 'tkinter'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            if package == 'cv2':
                import cv2
            elif package == 'PIL':
                from PIL import Image
            elif package == 'tkinter':
                import tkinter
            else:
                __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print("缺少以下依赖包:")
        for package in missing_packages:
            print(f"  - {package}")
        print("\n请运行以下命令安装依赖:")
        print("pip install -r requirements.txt")
        return False
    
    return True

def check_config():
    """检查配置文件"""
    config_file = current_dir / "config" / "default_config.json"
    if not config_file.exists():
        print(f"警告: 配置文件不存在 {config_file}")
        print("将使用默认配置")
    return str(config_file)

def main():
    """主函数"""
    try:
        # 设置日志
        logger = setup_logging()
        
        # 检查依赖
        if not check_dependencies():
            sys.exit(1)
        
        # 检查配置
        config_path = check_config()
        
        # 显示启动信息
        print("=" * 60)
        print("🎯 反无人机瞄准辅助系统")
        print("=" * 60)
        print("功能特性:")
        print("  ✓ 实时摄像头视频流")
        print("  ✓ YOLOv11目标检测")
        print("  ✓ 智能瞄准线系统")
        print("  ✓ 瞄准线校准功能")
        print("  ✓ 直观的GUI界面")
        print()
        print("快捷键:")
        print("  空格键  - 启动/停止摄像头")
        print("  C键     - 开始/完成校准")
        print("  R键     - 重置设置")
        print("=" * 60)
        print()
        
        # 创建并运行主应用
        logger.info("初始化主应用程序")
        app = MainWindow(config_path)
        
        logger.info("启动GUI界面")
        app.run()
        
        logger.info("程序正常退出")
        
    except KeyboardInterrupt:
        print("\n程序被用户中断")
        logger.info("程序被用户中断")
        
    except Exception as e:
        print(f"程序运行出错: {e}")
        logger.error(f"程序运行出错: {e}", exc_info=True)
        sys.exit(1)

if __name__ == "__main__":
    main()